$(function () {
  (function ($, win) {
    //字数限制
    $.fn.limitWords = function (max) {
      this.each(function () {
        var text = $.text($(this));
        if (text.length > max) {
          this.innerHTML = text.substring(0, max) + '...';
        }
      });
      return this;
    };
    //slide淡入淡出轮播
    $.fn.fadingSlide = function (options) {
      var settings = $.extend({
          'speed': '3000'
        }, options),
        that = $(this),
        btn = that.find('ul.slide-btn').find('li'),
        imgLi = that.find('ul.slide-img').find('li'),
        ind = 0,
        length = btn.length,
        timer = null;

      function play(ind) {
        btn.removeClass('on').eq(ind).addClass('on');
        imgLi.removeClass('up').eq(ind).addClass('up');
      }

      function witchplay(witch) {
        if (witch > 0) {
          if (ind === length - 1) {
            ind = 0;
            play(ind);
          } else {
            ind++;
            play(ind);
          }
        } else {
          if (ind === 0) {
            ind = length - 1;
            play(ind);
          } else {
            ind--;
            play(ind);
          }
        }
      }

      function autoplay(speed) {
        timer = setInterval(function () {
          witchplay(1);
        }, speed);
      }

      autoplay(settings.speed);
      btn.click(function () {
        ind = $(this).index();
        play(ind);
      });
      that.mouseover(function () {
        clearInterval(timer);
        timer = null;
      }).mouseout(function () {
        autoplay(settings.speed);
      });
      return this;
    };
    //无缝滚动
    $.fn.rolling = function (options) {
      var settings = $.extend({
        left: true,
        toLeft: true,
        speed: 1
      }, options);
      var that = this, oLi = that.find('li'), d = 0;

      function clearTime(fn) {
        var timer = setInterval(fn, 25);
        that.hover(function () {
          clearInterval(timer);
          timer = null;
        }, function () {
          timer = setInterval(fn, 25);
        });
      }

      if (settings.left) {
        var wi = oLi.length * oLi.outerWidth(true) * 2;
        that.css({width: wi}).html(that.html() + that.html())
          .parent().css({width: wi / 2, overflow: 'hidden'});
        var move = function () {
          if (settings.toLeft) {
            if (-d >= wi / 2) {
              d = 0;
              that.css('left', 0);
            } else {
              d = d - settings.speed;
              that.css('left', d);
            }
          } else {
            that.css('left', -wi / 2);
            if (d >= wi / 2) {
              d = 0;
              that.css('left', -wi / 2);
            } else {
              d = d + settings.speed;
              that.css('left', d - (wi / 2));
            }
          }
        };
        clearTime(move);
      } else {
        var He = oLi.length * oLi.outerHeight(true) * 2;
        that.css({height: He}).html(that.html() + that.html())
          .parent().css({height: He / 2, overflow: 'hidden'});
        var moveTop = function () {
          if (-d >= He / 2) {
            d = 0;
            that.css('top', 0);
          } else {
            d = d - settings.speed;
            that.css('top', d);
          }
        };
        clearTime(moveTop);
      }
      return this;
    };
    //左右滑动轮播
    $.fn.slideBanner = function (options) {
      var setting = $.extend({
          speed: 3000,
          arrow: true,
          hover: true
        }, options),
        that = this,
        bannerUi = that.find('.banner-ul'),
        bannerLi = bannerUi.find('li'),
        arrow = that.find('.banner-arrow'),
        nextBtn = that.find('.next'),
        prevBtn = that.find('.prev'),
        bannerBtn = that.find('.banner-btn').find('li'),
        timer = null,
        state = true,
        index = 0,
        sMove = bannerUi.outerWidth(),
        liNum = bannerLi.length;
      bannerLi.first().css('left', 0);
      function focus() {
        bannerBtn.removeClass('on');
        bannerBtn.eq(index).addClass('on');
      }

      if (!setting.arrow) {
        arrow.css('display', 'none');
      }
      bannerBtn.on('click', function () {
        var thisIndex = $(this).index();
        if (thisIndex > index) {
          bannerLi.eq(index).animate({left: -sMove});
          bannerLi.eq(thisIndex).css({left: sMove}).animate({left: 0});
          index = thisIndex;
          focus();
        } else if (thisIndex < index) {
          bannerLi.eq(index).animate({left: sMove});
          bannerLi.eq(thisIndex).css({left: -sMove}).animate({left: 0});
          index = thisIndex;
          focus();
        }
      });
      function play() {
        bannerLi.eq(index).animate({left: -sMove});
        index++;
        if (index === liNum) {
          index = 0;
          bannerLi.eq(index).css({left: sMove});
        }
        bannerLi.eq(index).css({left: sMove}).animate({left: 0});
        focus();
      }

      function autoPlay() {
        timer = setInterval(play, setting.speed);
      }

      if (setting.hover) {
        that.hover(function () {
          clearInterval(timer);
          timer = null;
        }, function () {
          autoPlay();
        });
      }
      prevBtn.click(function () {
        if (state === true) {
          state = false;
          bannerLi.eq(index).animate({left: sMove});
          index--;
          if (index < 0) {
            index = liNum - 1;
          }
          bannerLi.eq(index).css({left: -sMove}).animate({left: 0}, function () {
            state = true;
          });
          focus();
        }
      });
      nextBtn.click(function () {
        if (state === true) {
          state = false;
          bannerLi.eq(index).animate({left: -sMove});
          index++;
          if (index === liNum) {
            index = 0;
          }
          bannerLi.eq(index).css({left: sMove}).animate({left: 0}, function () {
            state = true;
          });
          focus();
        }
      });
      autoPlay();
      if (liNum === 1) {
        clearInterval(timer);
        timer = null;
      }
      return this;
    };
    //选项卡
    win.tab = function (btn, box) {
      if (box.length > 0) {
        box.eq(0).css('display', 'block');
        btn.click(function () {
          if (!$(this).hasClass('on')) {
            btn.removeClass('on');
            $(this).addClass('on');
            box.css('display', 'none').eq($(this).index()).fadeIn(200);
          }
        });
      }
      return this;
    };
    //广告浮动
    $.fn.floatAd = function (option) {
      var options = $.extend({
          width: "240",
          height: "150",
          speed: 18
        }, option),
        that = this,
        x = 0,
        y = 0,
        xin = true, yin = true;
      that.css({
        position: 'fixed',
        zIndex: 99999,
        width: options.width,
        height: options.height,
        backgroundColor: '#ffffff'
      });
      $('<span id="close-btn">&times;</span>').css({
        position: 'absolute',
        top: 0,
        right: -20,
        width: 20,
        height: 20,
        lineHeight: '20px',
        fontSize: '18px',
        textAlign: 'center',
        cursor: 'pointer',
        backgroundColor: '#dadada'
      }).appendTo(that);
      var DW = $(window).width(),
        DH = $(window).height(),
        OW = that.width(),
        OH = that.height(),
        L = 0,
        T = 0;

      function float() {
        x = x + (xin ? 1 : -1);
        if (x < L) {
          xin = true;
          x = L;
        }
        if (x > DW - OW - 1) {
          xin = false;
          x = DW - OW - 1;
        }
        y = y + (yin ? 1 : -1);
        if (y > DH - OH - 1) {
          yin = false;
          y = DH - OH - 1;
        }
        if (y < T) {
          yin = true;
          y = T;
        }
        that.css({
          'top': y,
          'left': x
        });
      }

      var timer = setInterval(float, options.speed);
      that.hover(function () {
        clearInterval(timer);
        timer = null;
      }, function () {
        if (that.css('display') !== 'none') {
          timer = setInterval(float, options.speed);
        }
      });
      $('#close-btn').click(function (e) {
        e.stopPropagation();
        that.css('display', 'none');
      });
      return this;
    };
  }(jQuery, window));

  //转义
  (function () {
    function htmlDecode(str) {
      if (str.length === 0) {
        return ""
      } else {
        var s = str.replace(/&gt;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/&#39;/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        s = s.replace(/<br>/g, "\n");
        return s;
      }
    }

    function htmlEncode(str) {
      if (str.length === 0) {
        return ""
      } else {
        var s = str.replace(/&/g, "&gt;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/ /g, "&nbsp;");
        s = s.replace(/\'/g, "&#39;");
        s = s.replace(/\"/g, "&quot;");
        s = s.replace(/\n/g, "<br>");
        return s;
      }
    }

    $('.tbtn').on('click', function () {
      $('.pp').html(htmlEncode($('.html').val()));
    });
  }());
  //头像上传裁剪插件
  (function () {
    $('.up-user-img').on('click', function (e) {
      e.stopPropagation();
      $('.upimg-box').fadeIn(200);
    });
    $('.box-bg').on('click', function (e) {
      e.stopPropagation();
      $('.upimg-box').fadeOut(200);
    });
    var options = {
      thumbBox: '.thumb-box',
      spinner: '.spinner',
      imgSrc: '../images/browser/360.png'
    };
    var cropper = $('.img-box').cropbox(options);
    $('#up-img').on('change', function () {
      if (typeof FileReader === "undefined") {
        $('.cropped').html('').append('<p>IE9以下浏览器暂不支持更换头像，请升级您的浏览器</p>');
      } else {
        var reader = new FileReader();
        reader.onload = function (e) {
          options.imgSrc = e.target.result;
          cropper = $('.img-box').cropbox(options);
        };
        reader.readAsDataURL(this.files[0]);
//        console.log(this.files);
        this.files[0] = [];
      }
    });
    $('#btnCrop').on('click', function () {
      var img = cropper.getDataURL();
      $('.big-img>img').attr('src', img);
      $('.small-img>img').attr('src', img);
      $('.cropped img').show();
    });
    $('#btnZoomIn').on('click', function () {
      cropper.zoomIn();
    });
    $('#btnZoomOut').on('click', function () {
      cropper.zoomOut();
    });
  }());
  //localStorage记住密码
  (function () {
    var username = $('#username');
    var psw = $('#password');
    var remBtn = $('#remember');
    if (psw.length > 0) {
      if (localStorage.getItem("username")) {
        username.val(localStorage.getItem("username"));
        /*$.ajax({
         url:'',
         type:'post',
         data:username.val()[0].atob(),
         success:function (data) {
         psw.val(data);
         }
         });*/
        remBtn.attr('checked', true);
      }
      remBtn.click(function () {
        if ($(this).is(':checked')) {
          localStorage.setItem("username", username.val());
//            localStorage.setItem("password", psw.val());
        } else {
          localStorage.removeItem('username');
//            localStorage.removeItem('password');

        }
      });
    }
  })();
  //下拉模糊筛选
  $('#select').chosen({
    disable_search_threshold: 0,
    no_results_text: "未找到",
    width: "95%",
    search_contains: true
  });
  $('.ajax').click(function () {
    console.log(1);
    $.ajax({
      type: 'get',
      url: 'http://datainfo.duapp.com/shopdata/getCar.php',
      dataType: 'jsonp',
      data: {
        serID: '123456'
      },
      success: function (data) {
        console.log(data);
      }
    });
  });
  $('.ad').floatAd({});

  //字数限制
  $('.notice-list a').limitWords(40);
  // 新闻栏目的淡入淡出轮播
  $('.slide-two').fadingSlide({speed: 3000});
  //首页底部无缝滚动
  $('ul.rolling').rolling({left: true, toLeft: true, speed: 1});
  //头部banner
  $('#banner').slideBanner({speed: 3500, arrow: false, hover: false});
});